package LeetCode;

public class DeadlockExample {
    private final Object lock1 = new Object();
    private final Object lock2 = new Object();

    public void firstThread() {
        synchronized (lock1) { // 线程1先获取lock1
//            Thread.sleep(3000);
            System.out.println("Thread 1: Holding lock 1...");
            System.out.println("Thread 1: Trying to lock 2...");
            synchronized (lock2) { // 线程1尝试获取lock2
                System.out.println("Thread 1: Holding lock 1 & 2");
            }
        }
    }

    public void secondThread() {
        synchronized (lock2) { // 线程2先获取lock2
//            Thread.sleep(3000);
            System.out.println("Thread 2: Holding lock 2...");
            System.out.println("Thread 2: Trying to lock 1...");
            synchronized (lock1) { // 线程2尝试获取lock1
                System.out.println("Thread 2: Holding lock 1 & 2");
            }
        }
    }

    public static void main(String[] args) {
        DeadlockExample example = new DeadlockExample();

        Thread t1 = new Thread(() -> {
            example.firstThread();
        });

        Thread t2 = new Thread(() -> {
            example.secondThread();
        });

        t1.start();
        t2.start();
    }
}